/*
Copyright 2010 Christian Dadswell
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package subscriber.chrisdadswell.co.uk;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

/*
 * KEY
 * 25 = %
 * 26 = &
 * 2F = /
 * 3A = :
 * 3D = =
 * 3F = ?
 */

// USES HTTP GOOGLE READER API
public class Func_GoogleReader {
	
	private static final String _APP_TAG = "Func_GoogleReader";
	private static final String _AGENT_STRING = "Subscriber";
	private static final String _GOOGLE_LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
	private static final String _READER_BASE_URL	= "http://www.google.com/reader/";
	private static final String _API_URL = _READER_BASE_URL + "api/0/";
	private static final String _TOKEN_URL = _API_URL + "token";
	private static final String _USER_INFO_URL = _API_URL + "user-info";
	
	private static final String _QUICKADD_URL = _API_URL + "quickadd";
	private static String _SUBSCRIPTION_URL = _API_URL + "subscription/edit";
	private static final String _EDIT_TAG_URL = _API_URL + "tag/edit";
	private static final String _RENAME_TAG_URL = _API_URL + "rename-tag";
	private static final String _DISABLE_TAG_URL = _API_URL + "disable-tag";
	
	private static final String _ATOM_URL = _READER_BASE_URL + "atom/";
	public static final String _READING_LIST_STATE = "user/-/state/com.google/reading-list";
	public static final String _READ_STATE = "user/-/state/com.google/read";

	public static final String _KEEP_UNREAD_STATE = "user/-/state/com.google/keep-unread";
	public static final String _FRESH_STATE = "user/-/state/com.google/fresh";
	public static final String _STARRED_STATE = "user/-/state/com.google/starred";
	public static final String _BROADCAST_STATE = "user/-/state/com.google/broadcast";
	private static final String _USER_LABEL = "user/-/label/";
	public static final String _FEED_PREFIX = "feed/";
	public static final String _TAG_LIST = _API_URL + "tag/list";
	public static final String _SUBSCRIPTION_LIST = "subscription/list";
	public static final String _UNREAD_COUNT_LIST = "unread-count";
	public static final int _MAX_NUM_ITEMS_TO_TAG = 250;

	public static String _AUTH = null;
	public static String _TOKEN = null;
	public static String _AUTHPARAMS = "GoogleLogin auth=";
	
	public static String _POSTDATA = null;
	public static String _STATUSCODE = null;
	public static String _USERINFO = null;
	public static String _RESPONSE = null;
	
/**
 * Returns a Google Authentication Key 
 * <p>
 * Requires a Google Username and Password to be sent in the GET headers 
 * to https://www.google.com/reader/api/0/tag/list
 * 
 * @param  GoogleGoogle_Username Google Username
 * @param  Google_Password Google Password
 * @return      Google authorisation token
 * @throws IOException 
 * @see         GetToken
 */
	//SUBSCRIPTION AND EDIT
	public static boolean Subscription(String Subscription_Type, String Subscription_Feed,
			String Subscription_Title, String Subscription_Label, String Google_Username, String Google_Password) throws IOException {
		Log.d(_APP_TAG, "METHOD: Subscription()");
		
		String _STR_PATTERN = "OK";
	    Pattern pattern = Pattern.compile(_STR_PATTERN);
	    Matcher matcher = pattern.matcher("");
	    String _TOKEN = Func_JSOUP.getGoogleToken(Google_Username, Google_Password);
	    String _AUTHKEY = Func_JSOUP.getGoogleAuthKey(Google_Username, Google_Password);
	    
	/*
	 *  PARAMS
	 *  s = feed/ <feedURL>
	 *  t = title
	 *  a = add label - s=http://xkcd.com/rss.xml&ac=edit&a=user/-/label/comics&token=<token>
	 *  R = ??
	 *  ac = subscribe | unsubscribe
	 *  T = Token
	 *  source = where are we coming from
	 */
		try{
			String _APIPOST = URLEncoder.encode("s", "UTF-8") + "=" + URLEncoder.encode("feed" + "/"+ Subscription_Feed, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("ac", "UTF-8") + "=" + URLEncoder.encode(Subscription_Type, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("a", "UTF-8") + "=" + URLEncoder.encode(_USER_LABEL + Subscription_Label, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("t", "UTF-8") + "=" + URLEncoder.encode(Subscription_Title, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("source", "UTF-8") + "=" + URLEncoder.encode("MOBILE_UI", "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("T", "UTF-8") + "=" + URLEncoder.encode(_TOKEN, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("R", "UTF-8") + "=" + URLEncoder.encode("/reader/m/directory?newSub=true&newStreamSub=feed" + URLEncoder.encode("/") + URLEncoder.encode(Subscription_Feed), "UTF-8");
		    //_APIPOST += "&" + URLEncoder.encode("R", "UTF-8") + "=" + URLEncoder.encode("/reader/m/directory?hl=en&newSub=true&newStreamSub=feed" + URLEncoder.encode("/") + URLEncoder.encode(Subscription_Feed), "UTF-8");
		    
		    URL url = new URL(_SUBSCRIPTION_URL);
		    Log.d(_APP_TAG, "VAR: URL: " + url);
		    URLConnection conn = url.openConnection();
		    conn.setUseCaches (false);
		    conn.setDoOutput(true);
		    conn.setRequestProperty("Authorization", _AUTHPARAMS + _AUTHKEY);
		    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		    wr.write(_APIPOST);
		    wr.flush();
	
		    // GET RESPONSE FROM THE POST
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    Log.d(_APP_TAG, "ACTION: Looking for Subscription Success");
		    while ((_RESPONSE = rd.readLine()) != null) {
		    	matcher.reset(_RESPONSE);
		        if (matcher.find()) {
		    		Log.d(_APP_TAG, "RESPONSE: "+Subscription_Type + " successful! (" + _RESPONSE + ")");
		    		return true;
		        }else{
		    		Log.d(_APP_TAG, "RESPONSE: "+ Subscription_Type + " unsuccessful (" + _RESPONSE + ")");
		    		return false;
		        	
		        }
		    }
		    wr.close();
		    rd.close();
		}catch (Exception e) {}
		return false;
	}
	
	public static String TagAPI(String Tag_Type, String Label_Title,String Google_Username, String Google_Password) throws IOException {
	    Log.d(_APP_TAG, "METHOD: TagAPI()");
		String _TAG_URL = null;
		
		String _USERID = Func_JSOUP.getGoogleUserID(Google_Username, Google_Password);
		String _TOKEN = Func_JSOUP.getGoogleToken(Google_Username, Google_Password);
		
		/*
		 *  PARAMS
		 *  s=user/14577161871823252783/label/<label name>
		 *  t=<label name>
		 *  T=<token>
		 */
			try{
				String _APIPOST = URLEncoder.encode("s", "UTF-8") + "=" + URLEncoder.encode("user" + "/"+ _USERID + "/label/" + Label_Title, "UTF-8");
			    _APIPOST += "&" + URLEncoder.encode("t", "UTF-8") + "=" + URLEncoder.encode(Label_Title, "UTF-8");
			    _APIPOST += "&" + URLEncoder.encode("T", "UTF-8") + "=" + URLEncoder.encode(_TOKEN, "UTF-8");
			    
			    if(Tag_Type == "edit") {
			    	_TAG_URL = _EDIT_TAG_URL;
			    }else if(Tag_Type == "disable") {
			    	_TAG_URL = _DISABLE_TAG_URL;
			    }else if(Tag_Type == "rename"){
			    	_TAG_URL = _RENAME_TAG_URL;
			    }
			    
			    URL url = new URL(_TAG_URL );
			    Log.d(_APP_TAG, "VAR: URL: " + url);
			    URLConnection conn = url.openConnection();
			    conn.setUseCaches (false);
			    conn.setDoOutput(true);
			    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			    wr.write(_APIPOST);
			    Log.d(_APP_TAG, "VAR: APIPost: " + _APIPOST);
			    wr.flush();
		
			    // GET RESPONSE FROM THE POST
			    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			    while ((_RESPONSE = rd.readLine()) != null) {
			    	if(_RESPONSE == "OK") {
					    Log.d(_APP_TAG, "RESPONSE: " + _RESPONSE);
			    		return _RESPONSE;
			    	}else{
			    		Log.d(_APP_TAG, "RESPONSE: " + _RESPONSE);
			    		return _RESPONSE;
			    	}
			    }
			    wr.close();
			    rd.close();
			}catch (Exception e) {}
			return null;
		}
	
	public static boolean TagShare(String Google_Username, String Google_Password, String UserID, String TagTitle, String ShareType) throws IOException {
		Log.d(_APP_TAG, "METHOD: TagShare()");
		String _TAG_URL = null;
		String Tag_Type = "edit";
		String _RESPONSE = null;
		
		String _TOKEN = Func_JSOUP.getGoogleToken(Google_Username, Google_Password);
		String _AUTHKEY = Func_JSOUP.getGoogleAuthKey(Google_Username, Google_Password);
		
		if(ShareType == "Public") {
			ShareType = "true";
		}else if(ShareType == "Private"){
			ShareType = "false";
		}
		/*
		MAKE TAG PUBLIC
		POST TO 
		http://www.google.com/reader/api/0/tag/edit?
		PARAMS
		s=user%2F14577161871823252783%2Flabel%2FVMWare&t=VMWare&pub=true&T=LuQOPECnfFbY_CagmRwmgg<token>
		 */
		try{
			String _APIPOST = URLEncoder.encode("s", "UTF-8") + "=" + URLEncoder.encode("user" + "/"+ UserID + "/label/" + TagTitle, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("t", "UTF-8") + "=" + URLEncoder.encode(TagTitle, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("pub", "UTF-8") + "=" + URLEncoder.encode(ShareType, "UTF-8");
		    _APIPOST += "&" + URLEncoder.encode("T", "UTF-8") + "=" + URLEncoder.encode(_TOKEN, "UTF-8");
		    
		    if(Tag_Type == "edit") {
		    	_TAG_URL = _EDIT_TAG_URL;
		    }else if(Tag_Type == "disable") {
		    	_TAG_URL = _DISABLE_TAG_URL;
		    }else if(Tag_Type == "rename"){
		    	_TAG_URL = _RENAME_TAG_URL;
		    }
		    
		    URL url = new URL(_TAG_URL );
		    Log.d(_APP_TAG, "VAR: URL: " + url);
		    URLConnection conn = url.openConnection();
		    conn.setUseCaches (false);
		    conn.setDoOutput(true);
		    conn.setRequestProperty("Authorization", _AUTHPARAMS + _AUTHKEY);
		    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		    wr.write(_APIPOST);
		    wr.flush();
		    _STATUSCODE = conn.getHeaderField(0);
		    Log.d(_APP_TAG, "VAR: Statuscode: " + _STATUSCODE);
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    
		    while ((_RESPONSE = rd.readLine()) != null) {
	            // GET ME THE AUTH VALUE
		    	System.out.println(_RESPONSE);
		    	if(Func_Strings.FindWordInString(_STATUSCODE, "OK")) {
		    		Log.d(_APP_TAG, "ACTION: Tag Marking " + TagTitle + " " + ShareType + " Successful");
		    		return true;
		    	}else{
		    		Log.d(_APP_TAG, "ACTION: Tag Marking " + TagTitle + " " + ShareType + " Unsuccessful");
		    		return false;
		    	}
		    }
		    wr.close();
		    rd.close();
		}catch (Exception e) {}
		return false;
	}
}